package com.supreme.threadserver.controller;

import com.supreme.commonboot.utils.AjaxResp;
import com.supreme.threadserver.threadpkg.VolatileThread;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;

@RestController
@RequestMapping(value = "volatile")
public class VolatileController {

    private final Map<String, Thread> threadMap = new ConcurrentHashMap<>();

    @GetMapping(value = "threadList")
    public AjaxResp threadList() {
        final List<String> threadList = new ArrayList<>(threadMap.keySet());
        return AjaxResp.instance(threadList);
    }

    @PostMapping(value = "createThread/{name}")
    public AjaxResp createThread(@PathVariable(value = "name") String name) {
        if (threadMap.containsKey(name)) {
            return AjaxResp.instance(-1, "thread exist");
        }

        Thread thread = new Thread(new VolatileThread());
        thread.setName(name);
        threadMap.put(name, thread);
        return AjaxResp.instance();
    }

    @PostMapping(value = "startThread/{name}")
    public AjaxResp startThread(@PathVariable(value = "name") String name) {
        Thread thread = threadMap.get(name);
        Optional.ofNullable(thread).ifPresent(Thread::start);
        return AjaxResp.instance();
    }

    @PostMapping(value = "stopThread/{name}")
    public AjaxResp stopThread(@PathVariable(value = "name") String name) {
        Thread thread = threadMap.get(name);
        Optional.ofNullable(thread).ifPresent(threadPresent -> {
            threadPresent.interrupt();
            threadMap.remove(name);
        });
        return AjaxResp.instance();
    }
}
